import React, { PureComponent } from 'react';
import { Select } from 'antd';
import { list } from '@/services/client';

const { Option } = Select;

class AppSelect extends PureComponent {
  state = {
    data: [],
    value: undefined,
  };

  componentDidMount() {
    const { defaultFirst, onChange } = this.props;
    list().then(response => {
      const { data } = response;
      this.setState({ data });
      if (data.length && defaultFirst) {
        this.setState({ value: data[0].clientId });
        if (onChange) onChange(data[0].clientId);
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.value !== nextProps.value) {
      this.setState({ value: nextProps.value });
    }
  }

  handleChange = value => {
    const { onChange } = this.props;
    this.setState({ value });
    if (onChange) onChange(value);
  };

  render() {
    const { props } = this;
    const { data, value } = this.state;
    return (
      <Select placeholder="请选择" value={value} {...props} onChange={this.handleChange}>
        {data
          .sort((d1, d2) => d1.showOrder - d2.showOrder)
          .filter(item => item.authorizedGrantTypes === 'client_credentials')
          .map(item => (
            <Option key={item.clientId} value={item.clientId}>
              {item.clientName}
            </Option>
          ))}
      </Select>
    );
  }
}

export default AppSelect;
